package com.itheima.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.SetmealDish;
import com.itheima.mapper.SetmealMapper;
import com.itheima.entity.Setmeal;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @email 1572178030@qq.com
 * @author:黄海宾
 * @date: 2023/2/4  15:56
 */
@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    public void SetmealWithDish(SetmealDto setmealDto) {
        //保存部分数据到setmeal中
        this.save(setmealDto);
        //取出setmealDishes中的数据保存到setmeal_dish对象中
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //得到setmeal中的id是于setmeal_dish对应的setmealId
/*        //select * from setmeal_dish where id = #{id}
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,setmealDto.getId());
        List<SetmealDish> list = setmealDishService.list(queryWrapper);*/

        List<SetmealDish> list = setmealDishes.stream().map(item -> {
            SetmealDish setmealDish = new SetmealDish();
            BeanUtils.copyProperties(item, setmealDish);
            setmealDish.setSetmealId(setmealDto.getId());
            return setmealDish;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(list);
    }

    @Override//先删除，在添加
    public void updateWithSetmeal(SetmealDto setmealDto) {
        //修改setmeal中的数据
        this.updateById(setmealDto);
        //修改setmealDish中的数据
        Long id = setmealDto.getId();

        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, id);
        //得到setmealDish中关联setmeal中的id值,并删除
        setmealDishService.remove(queryWrapper); //delete from setmeal_dish where setmeal_id = #{id}
        //setmealDishService.removeById(id);//根据id主键删除，只能删一个
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(id);
            setmealDishService.save(setmealDish);
        }
    }
}
